import jwt from '@/utils/jwt'
import { NextResponse } from 'next/server'
import { AUTH_TOKEN, ROUTE_LOGIN, ROUTE_DASHBOARD, COOKIE_MAX_AGE } from '@/config/settings'

export async function proxy(request) {
  const pathname = request.nextUrl.pathname;
  const isAdminPage = pathname.startsWith('/admin') && !pathname.startsWith('/admin/auth');
  const isAdminApi = pathname.startsWith('/api/admin') && !pathname.startsWith('/api/admin/auth');
  if (isAdminPage || isAdminApi) {
    const token = request.cookies.get(AUTH_TOKEN)?.value;
    if (!token) {
      if (isAdminApi) return NextResponse.json({ message: 'Not logged in', code: 1 }, { status: 401 });
      return NextResponse.redirect(new URL(ROUTE_LOGIN, request.url));
    }
    try {
      const payload = await jwt.verify(token);
      if (!payload) {
        if (isAdminApi) return NextResponse.json({ message: 'Invalid token', code: 1 }, { status: 401 });
        return NextResponse.redirect(new URL(ROUTE_LOGIN, request.url));
      }
      const {id, username, status, permissions}= payload.payload;
      if (status !== 0) {
        if (isAdminApi) return NextResponse.json({ message: 'Abnormal account status', code: 1 }, { status: 403 });
        return NextResponse.redirect(new URL(ROUTE_LOGIN, request.url));
      }
      const authApis = permissions.map(p => `/api${p}`);
      if (isAdminApi && !authApis.some(a => pathname.startsWith(a))) return NextResponse.json({message: 'No permission', code: 1 }, { status: 403 });
      if (isAdminPage && !permissions.some(p => pathname.startsWith(p))) return NextResponse.redirect(new URL(ROUTE_DASHBOARD, request.url));
      const newToken = await jwt.generate({id, username, status, permissions });
      const response = NextResponse.next();
      response.cookies.set(AUTH_TOKEN, newToken, { httpOnly: true, secure: false, maxAge: COOKIE_MAX_AGE, path: '/' });
      return response;
    } catch (e) {
      if (isAdminApi) return NextResponse.json({ message: 'Token parsing failed', code: 1 }, { status: 401 });
      return NextResponse.redirect(new URL(ROUTE_LOGIN, request.url));
    }
  }
}